package scatter.identifier.rest.login;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.extra.servlet.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import scatter.common.LoginUser;
import scatter.common.rest.security.IAuthenticationResultService;
import scatter.common.rest.security.LoginUserTool;
import scatter.identifier.pojo.login.IdentifierLoginUser;
import scatter.identifier.pojo.po.Identifier;
import scatter.identifier.rest.service.IIdentifierService;
import scatter.identifier.rest.service.impl.IdentifierServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * identifier 登录事件
 * </p>
 *
 * @author yangwei
 * @since 2021-09-28 10:26
 */
@Slf4j
@Component
public class IdentifierAuthenticationResultServiceImpl implements IAuthenticationResultService {

	@Autowired
	private IIdentifierService iIdentifierService;

	@Override
	public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
		LoginUser loginUser = LoginUserTool.getLoginUser();
		if (loginUser instanceof IdentifierLoginUser) {
			log.info("用户认证成功，更新用户 identifier 登录时间和ip，userId={}",loginUser.getId());
			Identifier identifier = ((IdentifierLoginUser) loginUser).getIdentifier();
			// 更新上次登录时间和登录ip
			Identifier identifierForUpdate = new Identifier()
					.setLastLoginAt(LocalDateTimeUtil.now())
					.setLastLoginIp(ServletUtil.getClientIP(httpServletRequest))
					;
			identifierForUpdate.setId(identifier.getId());
			iIdentifierService.updateById(identifierForUpdate);
		}
	}

	@Override
	public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {

	}
}
